<template>
  <div class="PayMode">
    <x-header @on-click-back="getback" :left-options="{backText: '',preventGoBack:true}">选择支付方式</x-header>
    <div style="padding:43px 0px 0px 0px">
      <div style="height:70px;display: flex;background: #fff;padding: 0 15px;align-items: center">
        <div style="flex: 1;text-align: left">
          <div style="font-size: 14px">支付金额</div>
          <!--<div style="font-size: 12px;color: #8C8C8C;">充值订单号：xxxxxx</div>-->
        </div>
        <div class="money">
          ￥{{payinfo.amount}}
        </div>
      </div>

      <div>
        <group>
          <radio :options="commonList" style="font-size: 14px" :value="checkvalue" @on-change="getchangevalue"></radio>
        </group>
      </div>
    </div>
    <div v-if="checkvalue=='alipay'&&payUrl!=''" style="padding: 12px;">
      <p>复制以下地址在浏览器中打开：</p>
      <div id="clonetxt" style="color:#28A4F7;font-size: 12px;width: 100%; word-wrap: break-word;word-break: normal;">
        {{payUrl}}
      </div>
      <x-button type="primary" id="copyBtn" class="toclone" data-clipboard-action="copy"
                data-clipboard-target="#clonetxt"
                @click.native="toclone">点击复制
      </x-button>
    </div>
    <x-button type="primary" class="saveinfo" v-if="checkvalue=='wechat'" @click.native="topaymoney">支付</x-button>
    <x-button type="primary" class="saveinfo" v-if="checkvalue=='alipay'&&payUrl==''" @click.native="topaymoney">支付
    </x-button>
  </div>
</template>

<script>
  import Vue from 'vue'
  import Clipboard from 'clipboard'
  import {Radio, Group, XButton, Checklist, XHeader} from 'vux'
  import wx from 'weixin-js-sdk'
  import Header from './../Header'
  import {Balance, SendSetMeal, Alipay} from '../../api/mine'

  export default {
    name: 'PayMode',
    data () {
      return {
        commonList: [{
          icon: 'static/icon/my_icon_wechat@3x.png',
          key: 'wechat',
          value: '微信支付'
        }, {
          icon: 'static/icon/my_icon_alipay@3x.png',
          key: 'alipay',
          value: '支付宝支付'
        }],
        checkvalue: 'wechat',
        type: 0,
        payinfo: {},
        payUrl: '',
        AlipayResult: null,
      }
    },
    beforeCreate () {
      // let config = {}
      // config.url = window.location.href
      // // 判断当前url是否存在?参数匹配符
      // if (!config.url.match(/\?/)) {
      //   location.replace(window.location.href.split('#')[0] + '?' + window.location.hash)
      //   return
      // }
    },
    created () {
      this.payinfo = this.$route.query
      this.type = this.$route.query.typeid
    },
    methods: {
      getchangevalue (value) {
        this.checkvalue = value
      },
      toclone () {
        let clipboard = new Clipboard('#copyBtn')
        clipboard.on('success', function (e) {
          Vue.$vux.confirm.show({
            content: `  <img src="static/icon/my_icon_pay_success@3x.png" style="width: 60px" alt="">
          <p>复制成功</p>`,
            showCancelButton: false,
            onConfirm () {

            }
          })
          e.clearSelection()
        })
      },
      topaymoney () {
        let _this = this
        if (this.payinfo.typeid == '0') {
          Vue.$vux.loading.show({
            text: '支付加载中...'
          })
          Balance({
            'amount': Number(_this.payinfo.amount),
            'payType': _this.checkvalue === 'wechat' ? '2' : '3',
            'shopId': _this.payinfo.shopid
          }).then(res => {
            if (res.data.status === 'success') {
              if (_this.checkvalue === 'wechat') {
                wx.ready(() => {
                  _this.jsSdk(res.data.data)
                })
              } else {
                Vue.$vux.loading.hide()
                _this.payUrl = res.data.data.payUrl
                // window.location.href = res.data.data.payUrl
                _this.alipaymoney(res.data.data.id)
              }
            } else {
              Vue.$vux.confirm.show({
                content: `  <img src="static/icon/pop_icon_!@3x.png" style="width: 60px" alt="">
          <p>${res.data.msg}</p>`,
                showCancelButton: false,
                onConfirm () {

                }
              })
            }
          })
        } else {
          SendSetMeal({
            'couponId': _this.payinfo.couponId,
            'payType': _this.checkvalue === 'wechat' ? '2' : '3',
            'seatType': _this.payinfo.settype,
            'setMealId': _this.payinfo.typeid,
            'shopId': _this.payinfo.shopid
          }).then(res => {
            if (res.data.status === 'success') {
              if (_this.checkvalue === 'wechat') {
                wx.ready(() => {
                  _this.jsSdk(res.data.data)
                })
              } else {
                Vue.$vux.loading.hide()
                _this.payUrl = res.data.data.payUrl
                // window.location.href = res.data.data.payUrl
                _this.alipaymoney(res.data.data.id)
              }
            } else {
              Vue.$vux.confirm.show({
                content: `  <img src="static/icon/pop_icon_!@3x.png" style="width: 60px" alt="">
          <p>${res.data.msg}</p>`,
                showCancelButton: false,
                onConfirm () {

                }
              })
            }
          })
        }
      },
      jsSdk (payOption) {
        let _this = this
        // 判断微信的WeixinJSBridge
        if (typeof WeixinJSBridge == 'undefined') {
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', _this.onBridgeReady, false)
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', _this.onBridgeReady)
            document.attachEvent('onWeixinJSBridgeReady', _this.onBridgeReady)
          }
        } else {
          _this.onBridgeReady(payOption)
        }
      },
      onBridgeReady (payOption) {
        let _this = this
        Vue.$vux.loading.hide()
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
            appId: payOption.appId, //公众号名称，由商户传入
            timeStamp: String(payOption.timeStamp), //时间戳，自1970年以来的秒数
            nonceStr: payOption.nonceStr, //随机串
            package: payOption.package, //prepay_id用等式的格式
            signType: payOption.signType, //微信签名方式：
            paySign: payOption.paySign, //微信签名
          },
          function (res) {
            // alert(JSON.stringify(res))
            if (res.err_msg == 'get_brand_wcpay_request:ok') {
              // 支付成功 返回成功页
              _this.$router.replace({
                name: 'PayResult',
                query: {
                  typeid: _this.type,
                  success: 1
                }
              })
            } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
              //  取消支付或者其他情况 get_brand_wcpay_request:cancel get_brand_wcpay_request:fail
              _this.$router.replace({
                name: 'PayResult',
                query: {
                  typeid: _this.type,
                  success: 2
                }
              })
            } else {
              _this.$router.replace({
                name: 'PayResult',
                query: {
                  typeid: _this.type,
                  success: 0
                }
              })
            }
          }
        )
      },
      //支付宝支付
      alipaymoney (id) {
        let _this = this
        _this.AlipayResult = setInterval(() => {
          Alipay({
            id: id
          }).then(res => {
            if (res.data.data && res.data.data.payStatus == 1) {
              clearInterval(_this.AlipayResult)
              _this.$router.replace({
                name: 'PayResult',
                query: {
                  typeid: _this.type,
                  success: 1
                }
              })
            } else if (res.data.data && res.data.data.payStatus != 1) {
              clearInterval(_this.AlipayResult)
              Vue.$vux.loading.hide()
              _this.$router.replace({
                name: 'PayResult',
                query: {
                  typeid: _this.type,
                  success: 0
                }
              })
            }
          })
        }, 3000)
      },
      getback () {
        let _this = this
        clearInterval(_this.AlipayResult)
        _this.$router.back(-1)
      }
    },
    components: {
      Header,
      Radio,
      Group,
      XButton,
      Checklist,
      XHeader
    },
  }
</script>

<style lang="less" type="text/less">
  .PayMode {
    font-size: 14px;
    .vux-no-group-title {
      margin-top: 8px;
    }
    .weui-cells:before {
      border: none;
    }
    .weui-cells:after {
      border: none;
    }
    .weui-cell:before {
      border: none;
    }
    .money {
      color: @common-color;
      font-size: 16px;
      flex: 1;
      text-align: right;
    }
    .weui-cell {
      padding: 12px 15px;
      border-bottom: 1px solid #F0F0F0;
    }
    .saveinfo {
      width: calc(100% - 15px);
      height: 42px;
      line-height: 42px;
      font-size: 16px;
      margin-top: 24px;
      color: #fff;
      border-radius: 42px;
      background-color: @common-color;
      position: fixed;
      left: 7px;
      bottom: 38px;
    }
    .toclone {
      width: 90px;
      height: 20px;
      line-height: 20px;
      font-size: 12px;
      margin-top: 24px;
      color: #fff;
      border-radius: 42px;
      background-color: @common-color;
    }
    .vux-header {
      background: #fff;
      position: fixed;
      z-index: 10;
      width: 100%;
      padding: 0;
      top: 0;
      .vux-header-title {
        color: #000;
        font-size: 16px;
        font-weight: 600;
      }
      .vux-header-left {
        .left-arrow {
          top: -7px;
          &:before {
            border-color: #000;
            border-width: 1px 0 0 1px;
            width: 10px;
            height: 10px;
          }
        }
      }
    }
  }
</style>
